package dao.impl;

import bean.Menu;
import dao.MiddleDao;
import util.DBUtil;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class MiddleDaoImpl extends DBUtil implements MiddleDao {

    @Override
    public int inserMiddle(int roleId, String[] menuIds) {
        int k =0;

        Connection connection = null;
        try {
            //MySQL默认操作模式就是autocommit自动提交模式。这里需要设置关闭SQL数据自动提交为false
            //创建一个连接
            connection = getConnection();
            //关闭自动提交
            connection.setAutoCommit(false);

            String sql = " insert into middle values(null,?,?) ";

            pps = getPps(sql);

            //批量新增数据
            for(String menuId:menuIds) {
                pps.setInt(1,roleId);
                pps.setString(2,menuId);
                pps.addBatch();

            }

            int[] i = pps.executeBatch();

            //提交数据
            connection.commit();
            //如果
            if (i.length==menuIds.length){
                //设置k=1表示数据提交成功
                k = 1;
            }

        } catch (SQLException throwables) {
            try {
                connection.rollback();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            throwables.printStackTrace();
        } finally {
            closeAll();
        }

        return k;
    }

    @Override
    public List<Integer> findById(int roleId) {

        List<Integer> menuIds= new ArrayList<>();

        try {
            String sql = " select * from middle where roleid=? ";

            List params = new ArrayList();
            params.add(roleId);

            resultSet = query(sql,params);

            while (resultSet.next()){

                int m = resultSet.getInt("menuid");

                menuIds.add(m);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            closeAll();
        }


        return menuIds;
    }

    /**
     * 中间表更新思路，先删后新增
     * @param roleId
     * @param menuIds
     * @return
     */
    @Override
    public int updateMenu(int roleId ,String[] menuIds) {

        int flag;
        int k = delete(roleId);
        if (k>0){

            flag = inserMiddle(roleId,menuIds);
            return flag;
        }

        return 0;
    }



    public int delete(int roleId) {

        int k =0;

        try {
            String sql = " delete from middle where roleid=? ";

            List params = new ArrayList();
            params.add(roleId);

            k = update(sql,params);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeAll();
        }

        return k;

    }
}
